import aesHelper from '@/utils/aesHelper'
import store from '@/store'
import { useAuthStore } from '@/store/auth'
import netconfig from '@/config/netconfig'

let authStore = useAuthStore(store)
/**
 * 初始化登录插件环境变量
 */
async function initLoginPlugin() {
  await authStore.loadOpenAndUnionId()
  let params = {
    unionid: authStore.accessUnionId,
    openid: authStore.accessOpenId,
    type: netconfig.MINI_TYPE,
    env: netconfig.PLUGIN_ENV,
    subType: 'HC3.0',
  }

  return new Promise<void>((resolve, reject) => {
    requirePlugin(
      'login-plugin',
      (loginPlugin) => {
        loginPlugin.initPlugin(params)
        resolve()
      },
      ({ mod, errMsg }) => {
        uni.hideLoading()
        uni.showToast({
          title: '加载异常，请稍后再试',
          icon: 'none',
        })
        reject()
      }
    )
  })
}

/**
 * 跳转登录插件登录注册页
 */
function jumpLoginPlugin(hasPhoneNo: boolean, fn?: 'navigateTo' | 'redirectTo' | 'reLaunch', obj?: object) {
  let params = obj ? `&param=${encodeURIComponent(JSON.stringify(obj))}` : ''
  if (hasPhoneNo) {
    authStore.removePartialUserInfo()
  } else {
    requirePlugin(
      'login-plugin',
      (loginPlugin) => {
        if (fn) {
          uni[fn]({
            url: `plugin://login-plugin/homeconnecLogin?isFromOmp=false&hasPhoneNo=${hasPhoneNo}${params}`,
          })
        } else {
          uni.navigateTo({
            url: `plugin://login-plugin/homeconnecLogin?isFromOmp=false&hasPhoneNo=${hasPhoneNo}${params}`,
          })
        }
      },
      ({ mod, errMsg }) => {
        uni.hideLoading()
        uni.showToast({
          title: '加载异常，请稍后再试',
          icon: 'none',
        })
      }
    )
  }
}

/**
 * 无手机号登录
 */
function noCiamIdLogin(fn?: 'navigateTo' | 'redirectTo' | 'reLaunch', obj?: object) {
  initLoginPlugin().then(() => {
    jumpLoginPlugin(false, fn, obj)
  })
}

export default {
  initLoginPlugin,
  noCiamIdLogin,
}
